//
//  TXHttpCache.m
//  TXKit
//
//  Created by zym on 2017/8/10.
//  Copyright © 2017年 Tincent. All rights reserved.
//

#import "TXHttpCache.h"

#if __has_include(<YYKit/YYKit.h>)
#import <YYKit/YYCache.h>
#import <YYKit/YYMemoryCache.h>
#import <YYKit/YYDiskCache.h>
#else
#import "YYCache.h"
#import "YYMemoryCache.h"
#import "YYDiskCache.h"
#endif

static NSString *const kTXHttpResponseCache = @"TXHttpResponseCache";

@implementation TXHttpCache
static YYCache *_dataCache;

+ (void)initialize {
    _dataCache = [YYCache cacheWithName:kTXHttpResponseCache];
}

+ (void)setHttpCache:(id)httpData url:(NSString *)url parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithUrl:url parameters:parameters];
    //异步缓存,不会阻塞主线程
    [_dataCache setObject:httpData forKey:cacheKey withBlock:nil];
}

+ (id)httpCacheForUrl:(NSString *)url parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithUrl:url parameters:parameters];
    return [_dataCache objectForKey:cacheKey];
}

+ (NSInteger)getAllHttpCacheSize {
    return [_dataCache.diskCache totalCost];
}

+ (void)removeAllHttpCache {
    [_dataCache.memoryCache removeAllObjects];
    [_dataCache.diskCache removeAllObjects];
}

+ (NSString *)cacheKeyWithUrl:(NSString *)url parameters:(NSDictionary *)parameters {
    if(!parameters || parameters.count == 0){return url;};
    
    // 将参数字典转换成字符串
    NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
    NSString *cacheKey = [NSString stringWithFormat:@"%@%@",url,paraString];
    
    return [NSString stringWithFormat:@"%ld",cacheKey.hash];
}

@end
